<template>
	<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower"
		@scroll="scroll">
		<!-- 上面的蓝色的卡片 -->
		<view class="user-info">
			<view class="info-container">
				<view class="user-title">
					<view class="left-image">
						<image src="/static/icons/u1469.png" mode=""></image>
					</view>
					<view class="right-text">
						<view class="top-name">张三</view>
						<view class="button-age">
							<view style="margin-right: 20rpx;">男</view>
							<view>28岁</view>
						</view>
					</view>
					<view class="tag-title" @click="toSignUser('bottom')">
						<view class="already-sign">切换签约人</view>
					</view>
				</view>
				<view class="user-num">
					<view style="margin-right: 20rpx;">身份证号</view>
					<view>233333333</view>
				</view>
				<view class="user-tel">
					<view style="margin-right: 20rpx;">联系电话</view>
					<view>333333333</view>
				</view>
				<view class="user-address">
					<view style="margin-right: 20rpx;">家庭住址</view>
					<view>成都市武侯区</view>
				</view>
			</view>
		</view>
		<!-- 下面的选项列表 -->
		<view class="list-info">
			<view class="table-user-info-other">
				<view class="list-text">签约机构</view>
				<view class="info-text">{{signText.organizationName}}</view>
			</view>
			<view class="table-user-info" @click="toTeam('bottom')">
				<view class="left-user-info">
					<view class="list-text">签约团队</view>
					<view class="info-text">{{signText.tesmName}}</view>
				</view>
				<view class="tight-arrow">
					<image src="/static/icons/u1334.png" mode=""></image>
				</view>
			</view>
			<view class="table-user-info" @click="toDoctor('bottom')">
				<view class="left-user-info">
					<view class="list-text">签约医生</view>
					<view class="info-text">{{signText.doctorName}}</view>
				</view>
				<view class="tight-arrow">
					<image src="/static/icons/u1334.png" mode=""></image>
				</view>
			</view>
			<view class="table-user-info" @click="toServicePackage('bottom')">
				<view class="left-user-info">
					<view class="list-text">服务包</view>
					<view class="info-text">{{signText.servicePackageName}}</view>
				</view>
				<view class="tight-arrow">
					<image src="/static/icons/u1334.png" mode=""></image>
				</view>
			</view>
			<view class="table-user-info-other">
				<view class="list-text">签约周期</view>
				<view class="info-text">1年</view>

			</view>
			<view class="table-user-info" @click="showPicker = true">
				<view class="left-user-info">
					<view class="list-text">生效日期</view>
					<view class="info-text">{{signText.effectiveDate}}</view>
				</view>
				<view class="tight-arrow">
					<image src="/static/icons/u1334.png"></image>
				</view>

			</view>
			<view class="table-user-info-other">
				<view class="list-text">费用</view>
				<view class="info-text" style="color: red;">￥{{servicePrice}}</view>
			</view>

			<view class="tips-item">
				<view class="list-text">备注</view>
				<view class="input-tips">
					<input type="text" placeholder="请填写备注" v-model="signForm.remark" />
				</view>
			</view>
		</view>
		<!-- 同意 -->
		<view style="display: flex; align-items: center;display:inline-block;padding: 30rpx 32rpx;">
			<checkbox-group @change="check">
				<label>
					<checkbox value="cb" color="#007aff" style="transform:scale(0.7)" />
					<text style="font-size:26rpx;color:#c9c9c9;font-weight: 400;">我已阅读并同意<text
							style="font-size:26rpx;color:#1877F2">《用户隐私政策》</text>
					</text>
				</label>
			</checkbox-group>
		</view>
		<view class="footer">

			<view class="quicky-payment" @click="onComfirm">提交申请</view>
		</view>
	</scroll-view>
	<view>
		<!-- 用户卡片的切换签约人 -->
		<uni-popup ref="popup" background-color="#fff" @change="change" v-if="signUserDialog">
			<view style="width: 100%; height: 500rpx;">
				<view class="select-doctor">请选择签约人</view>
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
					@scrolltolower="lower" @scroll="scroll">
					<view class="buttom-dialog">
						<view class="dialog-item" @click="getValue(item)">王富强</view>
					</view>
				</scroll-view>
				<view class="footer" @click="signUserDialog=false">取消</view>
			</view>
		</uni-popup>
		<!-- 团队的弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="change" v-if="teamDialog">
			<view style="width: 100%; height: 500rpx; overflow:hidden">
				<view class="select-doctor">请选择医生团队</view>
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" enable-back-to-top>
					<view class="buttom-dialog" v-for="item in organizationData.teams" :key="item._id">
						<view class="dialog-item" @click="teamValue(item)">{{item.name}}</view>
					</view>
				</scroll-view>
				<view class="footer" @click="teamDialog=false">取消</view>
			</view>
		</uni-popup>

		<!-- 医生的弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="change" v-if="doctorDialog">
			<view style="width: 100%; height: 500rpx;">
				<view class="select-doctor">请选择签约医生</view>
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
					@scrolltolower="lower" @scroll="scroll">
					<view class="buttom-dialog" v-for="item in doctorData" :key="item._id">
						<view class="dialog-item" @click="doctorValue(item)">{{item.name}}</view>
						<view class="doctor-role">{{item.roleId.name}}</view>
					</view>
				</scroll-view>
				<view class="footer" @click="doctorDialog=false">取消</view>
			</view>
		</uni-popup>
		<!-- 获取机构的服务包 根据机构id获取服务包-->
		<uni-popup ref="popup" background-color="#fff" @change="change" v-if="servicPackage">
			<view style="width: 100%; height: 500rpx; overflow:hidden,">
				<view class="select-doctor">请选择签约服务包</view>
				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" enable-back-to-top>
					<view class="buttom-dialog" v-for="item in organizationData.servicePacks" :key="item._id">
						<view class="dialog-item" @click="serviceValue(item)">{{item.name}}</view>
						<view class="service-price">￥{{item.price}}</view>
					</view>
				</scroll-view>
				<view class="footer" @click="servicPackage=false">取消</view>
			</view>
		</uni-popup>
	</view>
	<!-- 日期选择 -->
	<view class="item-box">
		<u-datetime-picker :show="showPicker" mode="date" v-model="selectedTime"
			@confirm="handleConfirm"></u-datetime-picker>
	</view>

	<!-- 点击确认申请之后的弹窗 -->
	<uni-popup ref="popup" type="center" borderRadius="20rpx 20rpx 20rpx 20rpx" style="text-align: center;"
		v-if="centerDialog">
		<view class="pop-center">
			<view class="pop-tip">
				签约申请提交后不可更改，确认提交吗？
			</view>
			<view class="pop-done">
				<view style="color: #999;" @click="closeDialog">取消</view>
				<view style="color: #2984f8;" @click="toSend">确认</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		onMounted,
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		getTeamDataApi
	} from '../../../api/team';
	import {
		fetchTeamDetailApi,
		getDoctorByTeamIdApi
	} from '../../../api/teamDoctor';
	import {
		getServicePackageByOranzApi
	} from '../../../api/servicePackage';
	import {
		addSignApi,
		getFullsignDetailApi,
		getSignDetailsApi
	} from '../../../api/sign';
	import {
		useUserStore
	} from '@/store/user.js';
	import {
		getOrganizationsApi
	} from '../../../api/organization';

	const useStore = useUserStore()

	// 日期选择
	const showPicker = ref(false);
	const selectedTime = ref(Date.now());

	const popup = ref()
	const type = ref('')
	const teamDialog = ref(false)
	const doctorDialog = ref(false)
	const servicPackage = ref(false)
	const signUserDialog = ref(false)
	const centerDialog = ref(false)
	// 判断点击过来的页面传递出的参数  
	// 点击主页面的立即签约进来 就没有签约id 就显示 从哪些页面挨着点过来的数据
	// 有签约id 就是申请续约的 就不用在表单里面显示数据 让他们重新选就好了
	const signId = ref('')
	onLoad((options) => {
		console.log('什么信息', options);
		console.log(useStore.signId);
		if (!options._id) {
			// 首页进的签约  给显示在页面上的表单重新赋值 signText 拿本地存储里面的数据
			getOrganDetail()
			getTeam()
			getDoctor()
		} else {
			// 如果传过来的id 有值 就是申请续约 回显表单的内容 
			// 传过来的是签约的id 根据签约的id 去获取签约详情 然后再回显在表单
			signId.value = options._id
			// getSignDetails() //拿到签约详情
			getFullDetail() //拿到完整的签约详情
		}
	})
	// 选择签约人
	const signUser = ref([])
	// 根据机构id  686f5dead42ba6a3947ac7b0 获取的团队数据
	const teamData = ref([])
	// 根据团队id 686f8d861c0e0785bff6223d 是李晓明那个团队的id 根据id 获取这个团队的医生
	const doctorData = ref([])
	// 根据机构id 获取服务包
	const serviceData = ref([])

	// 机构详情的数据
	const organizationData = ref({})
	// 保存申请时间的
	const currentTime = ref('');

	// 要回显在页面上的数据 显示文字的
	const signText = ref({
		organizationName: '',
		doctorName: '',
		tesmName: '',
		servicePackageName: '',
		effectiveDate: '',
		remark: '',
		price: ''
	})
	// 保存申请签约的表单的数据 686f8c4f44c7c46f75e72a54
	const signForm = ref({
		residentId: '',
		organizationId: '',
		teamId: '',
		doctorId: '',
		servicePackId: '',
		type: '',
		remark: '',
		applyTime: '',
		effectiveDate: ''
	})
	// 获取一个完整的签约详情

	const getFullDetail = () => {
		getFullsignDetailApi({
				_id: signId.value
			})
			.then(res => {
				if (res.code == 200) {
					console.log('这是一个完整的签约详情', res.data);
					uni.setStorageSync('organizationId', res.data.organizationId._id)
					getOrganDetail()
					// 将拿到的签约详情赋值给表单
					signText.value.effectiveDate = res.data.effectiveDate
					signText.value.doctorName = res.data.doctorId.name;
					signText.value.tesmName = res.data.teamId.name;
					signText.value.servicePackageName = res.data.servicePackId.name;
					signForm.value.organizationId = res.data.organizationId._id;
					signForm.value.teamId = res.data.teamId._id;
					signForm.value.doctorId = res.data.doctorId._id;
					signForm.value.servicePackId = res.data.servicePackId._id;
				}
			})
	}

	// 根据本地存储的机构id去获取机构详情 然后拿到详情赋值给要显示在页面上的
	const organizationId = uni.getStorageSync('organizationId')
	const getOrganDetail = () => {
		getOrganizationsApi({
				_id: organizationId
			})
			.then(res => {
				if (res.code == 200) {
					console.log('一个机构的详情吗', res.data);
					console.log(res.data.teams);
					signText.value.organizationName = res.data.name;
					signForm.value.organizationId = res.data._id;
					organizationData.value = res.data
				}
			})
	}
	// 取医生团队
	const teamId = uni.getStorageSync('doctorTeamId')
	const getTeam = () => {
		fetchTeamDetailApi({
				_id: teamId
			})
			.then(res => {
				if (res.code == 200) {
					console.log('一个团队的详情', res.data);
					signText.value.tesmName = res.data.name
					signForm.value.teamId = res.data._id
				}
			})
	}
	// 取医生
	const doctorName = uni.getStorageSync('doctorName')
	const getDoctor = () => {
		signText.value.doctorName = doctorName
	}

	const signIdData = ref('')
	watch(signIdData, () => {

		if (signIdData.value) {

			uni.navigateTo({
				url: `/minePackage/pages/apply-success/apply-success?_id=${signIdData.value}`
			})
		}
	})
	onMounted(() => {
		// getTeamData()
		getDoctorData()
		// getServicePackage()
	})
	// 发送新增签约的请求
	const addSign = () => {
		if (uni.getStorageSync('doctorId')) {
			addSignApi({
					...signForm.value,
					residentId: useStore.userInfo?._id,
					doctorId: uni.getStorageSync('doctorId'),
				})
				.then(res => {
					if (res.code == 200) {
						signIdData.value = res.data._id
						console.log(666, res.data);
						useStore.signId = res.data._id;

						console.log('添加签约成功', signForm.value);
						centerDialog.value = false


					}
				})
		} else {
			addSignApi({
					...signForm.value,
					residentId: useStore.userInfo?._id,
				})
				.then(res => {
					if (res.code == 200) {
						signIdData.value = res.data._id
						// console.log(res.data);
						useStore.signId = res.data._id;
						console.log('添加签约成功', signForm.value);
						centerDialog.value = false

						signText.value = {}
						signForm.value = {}
					}
				})
		}
	}
	// 根据团队获取医生
	const getDoctorData = () => {
		if (uni.getStorageSync('doctorTeamId')) {
			console.log('本地存储？？？团队数据？');
			getDoctorByTeamIdApi({
					teamId: uni.getStorageSync('doctorTeamId')
				})
				.then(res => {
					if (res.code == 200) {
						console.log(res.data);
						doctorData.value = res.data.rows
					}
				})
		} else {
			//根据签约详情里面的团队id去获取
			// getDoctorByTeamIdApi({
			// 		teamId: uni.getStorageSync('teamId')
			// 	})
			// 	.then(res => {
			// 		if (res.code == 200) {
			// 			console.log(res.data);
			// 			doctorData.value = res.data.rows
			// 		}
			// 	})
		}

	}
	// 发请求获取医生的团队
	const getTeamData = () => {
		if (uni.getStorageSync('organizationId')) {
			getTeamDataApi({
					organizationId: uni.getStorageSync('organizationId')
				})
				.then(res => {
					if (res.code == 200) {
						console.log(res.data);
						teamData.value = res.data.rows
					}
				})
		}
	}

	// 根据机构id去获取服务包
	// const getServicePackage = () => {
	// 	getServicePackageByOranzApi({
	// 			_id: '686f5dead42ba6a3947ac7b0'
	// 		})
	// 		.then(res => {
	// 			if (res.code == 200) {
	// 				console.log(res.data);
	// 				organizationData.value = res.data
	// 			}
	// 		})
	// }
	// 根据服务包id去获取详情

	const handleConfirm = (e) => {
		const date = new Date(e.value);
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		const day = date.getDate();
		const hour = date.getHours();
		console.log(`选择的时间为：${year}年${month}月${day}日`); //拿到选中的时间
		console.log(`${year}-${month}-${day}`);
		signForm.value.effectiveDate = year + '-' + month + '-' + day;
		signText.value.effectiveDate = year + '-' + month + '-' + day;
		showPicker.value = false;
	};

	// 点击底下的弹窗里面的值获取点击的值
	const getValue = (item) => {
		console.log(item);
		// 拿到选中的id 赋值给表单 让表单回显
		console.log(item._id);
		console.log(item.name);
	}

	// 团队的值
	const teamValue = (item) => {
		console.log(item);
		console.log(item.name + item._id);
		signForm.value.teamId = item._id;
		signText.value.tesmName = item.name
		teamDialog.value = false
	}
	// 医生的值
	const doctorValue = (item) => {
		console.log(item);
		console.log(item.name + item._id); //拿到选中的id 和name 赋值给表单回显
		signForm.value.doctorId = item._id
		signText.value.doctorName = item.name //拿到名字 回显到页面上
		doctorDialog.value = false
	}
	// 服务包的值
	const servicePrice = ref('')
	const serviceValue = (item) => {
		console.log(item);
		console.log(item.name + item._id);
		servicePrice.value = item.price
		signForm.value.servicePackId = item._id
		signText.value.servicePackageName = item.name
		servicPackage.value = false
	}
	const change = (e) => {
		console.log(`当前是${e.type},状态${e.show}`);
	}

	const toTeam = (popupType) => {
		type.value = popupType;
		popup.value?.open(popupType)
		teamDialog.value = true

	}
	const toDoctor = (popupType) => {
		type.value = popupType;
		popup.value?.open(popupType)
		doctorDialog.value = true
	}
	const toServicePackage = (popupType) => {
		type.value = popupType;
		popup.value?.open(popupType)
		servicPackage.value = true
	}
	const toSignUser = (popupType) => {
		type.value = popupType;
		popup.value?.open(popupType)
		signUserDialog.value = true
	}
	// 确认申请的弹窗
	const onComfirm = () => {
		popup.value?.open()
		centerDialog.value = true
	}
	const closeDialog = () => {
		centerDialog.value = false
	}
	// 关闭底下的弹窗
	const closeProp = () => {
		popup.value?.close()
	}
	const close = () => {
		popup.value?.close()
	}
	const toSend = () => {
		signForm.value.applyTime = getCurrentDateTime();
		addSign()


	}
	// 生成当前时间（格式：YYYY-MM-DD HH:mm）
	const getCurrentDateTime = () => {
		const now = new Date();
		// 获取各时间组件
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
		const day = String(now.getDate()).padStart(2, '0'); // 日期补零
		const hours = String(now.getHours()).padStart(2, '0'); // 小时补零
		const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
		// 组合成目标格式
		return `${year}-${month}-${day} ${hours}:${minutes}`;
	};
</script>

<style scoped lang="scss">
	// 中间弹出层
	.pop-center {
		width: 520rpx;
		height: 352rpx;
		background-color: #fff;
	}

	.pop-tip {
		height: 264rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		line-height: 56rpx;
		color: #333;
		padding: 0rpx 40rpx;
		font-family: 'SourceHanSansSC-Regular', '思源黑体';
		font-weight: 400;
	}

	.pop-done {
		height: 88rpx;
		border-top: 1px solid #e6e6e6;
		display: flex;
	}

	.pop-done view {
		height: 88rpx;
		width: 260rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}

	.scroll-Y-team {
		height: 1600rpx;
	}

	.buttom-dialog {
		width: 100%;
		height: 88rpx;
		border-bottom: 1rpx solid #e5e5e5;
		display: flex;
		justify-content: center;
		align-items: center;
		white-space: nowrap;

		.dialog-item {
			font-size: 32rpx;
			color: #1877E2;

		}
	}

	.scroll-Y {
		height: 1600rpx;
	}

	.user-info {
		margin: 30rpx 32rpx;
		width: 670rpx;
		height: 352rpx;
		background-color: #2984f8;
		// margin-top: 20rpx;
		border-radius: 20rpx;
	}

	.info-container {
		padding: 30rpx 30rpx;

	}

	.left-image {
		image {
			width: 112rpx;
			height: 112rpx;
		}
	}


	.right-text {
		margin-left: 30rpx;
		margin-top: 20rpx;
	}

	.user-title {
		display: flex;
		position: relative;
	}

	.top-name {
		font-size: 40rpx;
		color: #ffffff;
	}

	.button-age {
		font-size: 24rpx;
		color: #ffffff;
		display: flex;
	}

	.user-num,
	.user-tel,
	.user-address {
		font-size: 24rpx;
		color: #ffffff;
		display: flex;
		margin: 20rpx 0;
	}

	.tag-title {
		width: 160rpx;
		height: 48rpx;
		background-color: #ffffff;
		border-radius: 40rpx;
		position: absolute;
		left: 440rpx;
		top: 20rpx;
	}

	.already-sign {
		font-size: 24rpx;
		color: #006EF1;
		text-align: center;
		line-height: 48rpx;

	}

	.list-info {
		padding: 0 32rpx;
	}

	.table-user-info {
		width: 710rpx;
		height: 88rpx;
		border-bottom: 1rpx solid #e5e5e5;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.table-user-info-other {
		width: 100%;
		height: 88rpx;
		border-bottom: 1rpx solid #e5e5e5;
		display: flex;
		align-items: center;

		.list-text {
			width: 112rpx;
			height: 40rpx;
			font-size: 28rpx;
			color: #999999;

		}

		.info-text {
			font-size: 28rpx;
			color: #333333;
			margin-left: 30rpx;
		}
	}

	.tips-item {
		width: 100%;
		height: 256rpx;
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		border-bottom: 1rpx solid #e5e5e5;

		.list-text {
			width: 112rpx;
			height: 40rpx;
			font-size: 28rpx;
			color: #999999;

		}
	}

	.input-tips {
		width: 484rpx;
		height: 216rpx;
		background-color: #f2f2f2;
		border-radius: 20rpx;

		input {
			display: inline-block;
			padding: 20rpx 30rpx;
		}
	}



	.left-user-info {
		display: flex;
	}

	.list-text {
		width: 112rpx;
		height: 40rpx;
		font-size: 28rpx;
		color: #999999;

	}

	.info-text {
		font-size: 28rpx;
		color: #333333;
		margin-left: 30rpx;
	}

	.tight-arrow {


		image {
			width: 14rpx;
			height: 24rpx;
			margin-right: 32rpx;
		}
	}

	.select-doctor {
		width: 100%;
		height: 88rpx;
		border-bottom: 1rpx solid #e5e5e5;
		font-family: 'PingFangSC-Regular', 'PingFang SC';
		font-weight: 400;
		text-align: center;
		line-height: 88rpx;
		font-size: 24rpx;
		color: #999999;
	}

	.doctor-role {
		font-size: 28rpx;
		color: #999999;
		margin-left: 10rpx;
	}

	.service-price {
		font-size: 28rpx;
		color: #FA746b;
		margin-left: 10rpx;
	}

	.footer {
		width: 100%;
		height: 160rpx;
		border-top: 10rpx solid #f7fafd;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		color: #999999;
		line-height: 160rpx;
	}

	.quicky-payment {
		width: 670rpx;
		height: 88rpx;
		background-color: #2984f8;
		border-radius: 20rpx;
		text-align: center;
		line-height: 88rpx;
		font-size: 32rpx;
		color: #ffffff;
	}
</style>
<style>
	page {
		background-color: #f7fafd;
		/* 自定义颜色 */
	}
</style>